import React from 'react';
import { Layout, Form, Input, Button, Checkbox, message } from 'antd';
import { useNavigate, Link } from "react-router-dom";
import { login } from 'src/api/getData'
import styles from './index.module.less';

const { Header, Content, Footer } = Layout;

const Login = () => {

    const navigate = useNavigate();

    async function onFinish(values) {
        const { user_name, password } = values
        try {
            const res = await login({
                user_name,
                password
            })
            if (res.code === 0) {
                message.success('登录成功')
                navigate("/portal/home");
            } else {
                message.error(res.message)
            }
        } catch (error) {
            message.error(error.message)
        }
    }

    function onFinishFailed(errorInfo) {
        console.log('Failed:', errorInfo);
        message.error('请输入正确的用户名密码')
    }

    return (
        <Layout>
            <Header className={styles.header}>
                欢迎来到后台管理系统！请登录
            </Header>
            <Content className={styles.content}>
                <Form
                    className={styles.form}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    name="basic"
                    initialValues={{
                        user_name: 'zhangsan',
                        password: '123456',
                        remember: true
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                >
                    <Form.Item
                        label="用户名"
                        name="user_name"
                        rules={[{ required: true, message: '请输入用户名!' }]}
                    >
                        <Input placeholder="请输入用户名" />
                    </Form.Item>
                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[{ required: true, message: '请输入密码!' }]}
                    >
                        <Input.Password placeholder="请输入密码" />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4, span: 12 }} name="remember" valuePropName="checked">
                        <Checkbox>记住密码</Checkbox>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4, span: 12 }}>
                        <Button type="primary" htmlType="submit">
                            登录
                        </Button>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4, span: 12 }}>
                        没有账号？<Link to="/register">立即注册</Link>
                    </Form.Item>
                </Form>
            </Content>
            <Footer className={styles.footer}>liviuscn@qq.com</Footer>
        </Layout>
    );
};

export default Login